//
//  DAMessageViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/6/24.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAMessageViewController.h"
#import "DAMessageCell.h"
#import "DAHeader.h"
#import "DAMessageModel.h"
#import "DAMessageDetailViewController.h"
#import "DALocalMessageSingletonModel.h"
#import "DASystemMessageTableViewCell.h"
#import "DATabBarViewController.h"
#import "JPUSHService.h"
#import "DADataHandel.h"


typedef void(^SuccessfulBlock)(void);

@interface DAMessageViewController()<UITableViewDelegate,UITableViewDataSource>{
    NSMutableArray *dataArray;
    BOOL isRefresh;
    NSInteger pageCount;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, copy) SuccessfulBlock Block;
@end
@implementation DAMessageViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidLoad{
    [super viewDidLoad];
    dataArray = [[NSMutableArray alloc]init];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Message" style:UIBarButtonItemStylePlain target:self action:@selector(clickMessage)];
    self.navigationItem.leftBarButtonItem.enabled = NO;
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    [self createTableView];
    //[self.tableView.mj_header beginRefreshing];
    [self addNotification];
    [self prepareLoaclData];
    pageCount = 1;
    
    
}
- (void)clickMessage{
    
}

- (void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateModel) name:@"NotificationUpData" object:nil];
}
- (void)updateModel{
    pageCount = 1;
    [self prepareLoaclData];
    [self.tableView reloadData];
}
- (void)createTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tabBarController.tabBar.translucent = YES;
    //
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld@3x", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld@3x", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21@3x"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer.hidden = NO;
}
#pragma mark - 下拉刷新
- (void)refreshData{
    isRefresh = YES;
    pageCount = 0;
    [self refreshLocalData];
}
#pragma mark - 上拉
- (void)loadMoreData{
    isRefresh = NO;
   // [self prepareMessageData];
   // pageCount++;
    [self refreshLocalData];
}
#pragma mark - 准备数据
- (void)prepareLoaclData{
    DALocalMessageSingletonModel *model = [DALocalMessageSingletonModel sharedDALocalMessageSingletonModel];
    dataArray = (NSMutableArray *)[model returnModelArray];
    if (dataArray.count >= 20) {
        self.tableView.mj_footer.hidden = NO;
    }else{
        self.tableView.mj_footer.hidden = YES;
    }
    
    [self.tableView reloadData];
}
#pragma mark -刷新数据
- (void)refreshLocalData{
    DALocalMessageSingletonModel *model = [DALocalMessageSingletonModel sharedDALocalMessageSingletonModel];
  //  [model prepareDataWithUserID:self.userID];
    // 从本地取出 lastReplyID
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *lastID = [userDefaults objectForKey:@"lastReplyID"];
    __weak typeof(self)weakSelf = self;
    NSString *page = [NSString stringWithFormat:@"%ld", (long)pageCount];
    [model prepareDataWithUserID:self.userID lastReplyID:lastID pageNumber:page  block:^(BOOL isSuccessful) {
        if (isSuccessful){
            // 刷新
            if (isRefresh) {
                dataArray = (NSMutableArray *)[model returnModelArray];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"isBorrowSuccessful" object:nil];
                if (dataArray.count >= 20) {
                    weakSelf.tableView.mj_footer.hidden = NO;
                }else{
                    weakSelf.tableView.mj_footer.hidden = YES;
                }
                pageCount++;
            }else{
                if ([[model returnMoreDataArray] count] < 20) {
                    weakSelf.tableView.mj_footer.hidden = YES;
                }else{
                    weakSelf.tableView.mj_footer.hidden = NO;
                }
                [dataArray addObjectsFromArray:[model returnMoreDataArray]];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_footer endRefreshing];
                pageCount++;
            }
        }else{
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            weakSelf.tableView.mj_footer.hidden = YES;
        }
    }];
//    [self.tableView reloadData];
//    [self.tableView.mj_header endRefreshing];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CleanMessageBadge" object:nil];
    // 清除消息的badge
    [JPUSHService resetBadge];
   
}

#pragma mark - tableView编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSLog(@"ss");
        // 删除评论
        DALocalMessageSingletonModel *model = [dataArray objectAtIndex:indexPath.row];
        NSLog(@"%@", model.replyID);
        typeof(self) weakSelf = self;
        [self deleteMessage:model.replyID Block:^{
            [dataArray removeObjectAtIndex:indexPath.row];
           // [tableView reloadData];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
            // 本地数据同步删除
            [weakSelf deleteLocalMessage:indexPath.row widthModel:model];
        }];
    }
}
#pragma mark - 本地存储的数据同步删除
- (void)deleteLocalMessage:(NSInteger)index widthModel:(DALocalMessageSingletonModel *)model{
    DALocalMessageSingletonModel *Localmodel = [DALocalMessageSingletonModel sharedDALocalMessageSingletonModel];
    [Localmodel changeLoacalMessageDataWithIndex:index withModel:model];
}
#pragma mark 删除消息
- (void)deleteMessage:(NSString *)ID Block:(SuccessfulBlock)block{
    NSString *url = DADeleteMessageURL;
    NSDictionary *dic = @{@"deleteID": ID};
    NSString *str = NSLocalizedString(@"deletefilefail", nil);
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if (result && [result[@"result"] isEqualToString:@"true"]) {
            block();
        }else{
            NSLog(@"删除失败");
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
            if ([result[@"result"] isEqualToString:@"false"]) {
                [SVProgressHUD showErrorWithStatus:str];
            }
            
        }
    }];
    
}

#pragma mark - tableViewDelegate&Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DAMessageModel *model = [dataArray objectAtIndex:indexPath.row];
    if ([model.replyType isEqualToString:@"1"]) {
        CGFloat height = [self heightWithText:model.replyContent Width:[UIScreen mainScreen].bounds.size.width - 80 Font:14];
        return 60 + height;
    }else{
        
        return 80;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DAMessageModel *model = [dataArray objectAtIndex:indexPath.row];
    // 1 是系统消息  0是评论回复的消息
    if ([model.replyType isEqualToString:@"1"]) {
        DASystemMessageTableViewCell *systemCell = [tableView dequeueReusableCellWithIdentifier:@"DASystem"];
        if (systemCell == nil) {
            systemCell = [[DASystemMessageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DASystem"];
        }
        systemCell.systemBackgroundView.backgroundColor = [UIColor supportGreenColor];
        systemCell.systemImageView.image = [UIImage imageNamed:@"speaker@3x"];
        systemCell.systemBackgroundView.layer.cornerRadius = 3;
        systemCell.systemBackgroundView.clipsToBounds = YES;
        systemCell.nameLabel.text = model.replyUser;
        systemCell.nameLabel.textColor = [UIColor supportGreenColor];
        [systemCell.messageLabel setText:model.replyContent fitToContent:YES];
        systemCell.messageLabel.textColor = [UIColor colorWithHexString:bookNameColor];
        systemCell.dateLabel.text = model.replyDate;
        systemCell.dateLabel.textColor = [UIColor colorWithHexString:timeColor];
        systemCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return systemCell;
    }else{
            DAMessageCell *messageCell = [tableView dequeueReusableCellWithIdentifier:@"DAMessageCell"];
            if (messageCell == nil) {
                messageCell = [[DAMessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DAMessageCell"];
            }
        
            [messageCell.faceImage sd_setImageWithURL:[NSURL URLWithString:model.replyUserFace] placeholderImage:[UIImage imageNamed:@"holderface"] options:SDWebImageRefreshCached];
            messageCell.faceImage.layer.cornerRadius = 3;
            messageCell.faceImage.clipsToBounds = YES;
            messageCell.nameLabel.text = model.replyUser;
            messageCell.nameLabel.textColor = [UIColor supportGreenColor];
            [messageCell.messageLabel setText:model.replyContent fitToContent:NO];
            messageCell.messageLabel.textColor = [UIColor colorWithHexString:bookNameColor];
            messageCell.dateLabel.textColor = [UIColor colorWithHexString:timeColor];
            messageCell.dateLabel.text = model.replyDate;
        
        return messageCell;
        
    }
    
}




//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    DAMessageDetailViewController *messageDetail = [self.storyboard instantiateViewControllerWithIdentifier:@"MESSAGEDETAIL"];
//    messageDetail.hidesBottomBarWhenPushed = YES;
//    messageDetail.messageID = @"chuanru";
//    [self.navigationController pushViewController:messageDetail animated:YES];
//    
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    DAMessageModel *model = [dataArray objectAtIndex:indexPath.row];
    if ([model.replyType isEqualToString:@"0"]) {
        DAMessageDetailViewController *messageDetailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MESSAGEDETAIL"];
        messageDetailVC.hidesBottomBarWhenPushed = YES;
        messageDetailVC.timelineID = model.replyTimeline;
        [self.navigationController pushViewController:messageDetailVC animated:YES];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}
#pragma mark - 将数据存储到本地
- (void)archiveToLocalWithData:(NSDictionary *)data{
    // 创建文件夹路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"MyMessage"];
    BOOL isSuccess = [data writeToFile:path atomically:YES];
   // filePath = path;
    if (isSuccess) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setBool:YES forKey:@"isArichiveData"];
    }
}
#pragma mark - 从本地取出数据
- (NSDictionary *)getLocalDataWithPath:(NSString *)path{
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    return dic;
}
#pragma mark - 判断本地有没有数据
- (BOOL)localDataIsExist{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL isExist = [userDefaults boolForKey:@"isArichiveData"];
    return isExist;
}


@end
